package cn.com.unionlife.hy.system.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import cn.com.unionlife.hy.core.exception.BusinessException;
import cn.com.unionlife.hy.system.mapper.OrgMapper;
import cn.com.unionlife.hy.system.mapper.UserMapper;
import cn.com.unionlife.hy.system.service.OrgQryService;
import cn.com.unionlife.hy.system.vo.OrgVO;
import cn.com.unionlife.hy.system.vo.UserVO;

@Service("orgQryService")
public class OrgQryServiceImpl implements OrgQryService {

	@Resource(name = "orgMapper")
	private OrgMapper orgMapper;
	@Resource(name = "userMapper")
	private UserMapper userMapper;

	@Override
	public List<OrgVO> getUserAuthorizedOrg(String userId, String name,
			boolean admin, boolean tree) throws BusinessException {
		List<OrgVO> retVal = new ArrayList<OrgVO>();
		if (StringUtils.isNotBlank(userId)) {
			UserVO user = userMapper.getById(userId);
			if (user != null) {
				List<OrgVO> orgList = new ArrayList<OrgVO>();
				// 当要显示管理员权限组织时，超级管理员具有所有组织的权限
				if (admin & user.isAdmin()) {
					List<OrgVO> orgs = orgMapper.findAll();
					if (orgs != null) {
						orgList.addAll(orgs);
					}
				} else {
					// 分配的组织
					List<OrgVO> authorizedOrg = orgMapper
							.findUserAuthorizedOrgByName(userId, name);
					if (authorizedOrg != null) {
						orgList.addAll(authorizedOrg);
					}
				}
				// 构造成树结构
				if (tree) {
					// 构造树结构
					Map<String, OrgVO> orgIdMap = new HashMap<String, OrgVO>();
					for (OrgVO org : orgList) {
						orgIdMap.put(org.getUm_organ_id(), org);
					}
					for (OrgVO org : orgList) {
						OrgVO parentOrg = org.getParent() == null ? null
								: orgIdMap
										.get(org.getParent().getUm_organ_id());
						if (parentOrg != null) {
							parentOrg.getChildren().add(org);
						} else {
							retVal.add(org);
						}
					}
				} else {
					retVal.addAll(orgList);
				}

			}
		}
		return retVal;
	}

	@Override
	public List<OrgVO> getUserAuthorizedOrg(String userId , boolean tree)throws BusinessException {
		List<OrgVO> retVal = new ArrayList<OrgVO>();
		if (StringUtils.isNotBlank(userId)) {
			UserVO user = userMapper.getById(userId);
			if (user != null) {
				// 当要显示管理员权限组织时，超级管理员具有所有组织的权限
				// 分配的组织
				List<OrgVO> authorizedOrg = orgMapper.findUserAuthorizedOrg(userId);
				if (authorizedOrg != null) {
					retVal.addAll(authorizedOrg);
				}
			}
		}
		return retVal;
	}
}
